﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Inventory;
using BasicInformation.ApiWrite.Application.Command.Location;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Inventory
{
    public class AddInventoryHandler : IRequestHandler<AddInventoryCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly DatabaseContext db;
        private readonly ILogger<AddInventoryHandler> logger;

        public AddInventoryHandler(IMapper mapper,DatabaseContext db,ILogger<AddInventoryHandler> logger)
        {
            this.mapper = mapper;
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddInventoryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> result = new ApiResult<int>();
                var model = mapper.Map<InventorysModel>(request);
                int r = await db.SqlSugar.Insertable(model).ExecuteCommandAsync();
                if (r > 0)
                {
                    result.Msg = "库存盘点添加成功";
                    result.Data = r;
                    result.Code = ApiEnum.OK;
                    logger.LogInformation(result.Msg);
                }
                else
                {
                    result.Msg = "库存盘点添加失败";
                    result.Data = r;
                    result.Code = ApiEnum.Fail;
                    logger.LogError(result.Msg);
                }
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
            
        }
    }
}
